﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Embedded_Sensor_Cloud
{
    public class ServerClientConnection
    {
        private Socket socket;
        private PluginManager pluginManager;
        public ServerClientConnection(Socket s, PluginManager pluginManager)
        {
            socket = s;
            this.pluginManager = pluginManager;
        }
        public void Run()
        {
            IPlugin.Request req = null;
            try
            {
                req = new IPlugin.Request(socket);
                bool b = req.Parse();

                //Kein gültiger Request
                if (b == false)
                    return;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (socket != null)
                    socket.Close();
                return;
            }

            //--- START DEBUG PARAMETERS ---
                    var getParameters = req.ReqUrl.ParameterList;
                    foreach (KeyValuePair<string, string> pair in getParameters)
                    {
                        Console.WriteLine("{0}, {1}",
                        pair.Key,
                        pair.Value);
                    }
                    if (req.Method.ToUpper().Equals("POST"))
                    {
                        Console.WriteLine("Post-Variablen:");
                        foreach (KeyValuePair<string, string> pair in req.ReqPostVars.ParameterList)
                        {
                            Console.WriteLine("{0}, {1}",
                            pair.Key,
                            pair.Value);
                        }
                    }
            //--- ENDE DEBUG ---

            //PluginManager Request übergeben und anschließend Response an Client senden
            IPlugin.Response resp = pluginManager.HandleRequest(req);
            resp.sendResponse();

        }
    }
}
